package org.phoenix.mall.admin.config.interceptors;

import org.phoenix.mall.admin.common.utils.AuthUtil;
import org.phoenix.mall.admin.config.annotations.AuthRequired;
import org.phoenix.mall.admin.pojo.User;
import org.phoenix.mall.admin.service.UserService;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthorizationInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
//        if (method.isAnnotationPresent(AuthIgnore.class) || handlerMethod.getBeanType().isAnnotationPresent(AuthIgnore.class)) {
//            return true;
//        }

        if (method.isAnnotationPresent(AuthRequired.class) || handlerMethod.getBeanType().isAnnotationPresent(AuthRequired.class)) {
            String token = request.getHeader("Authorization");
            if (token == null) {
                throw new RuntimeException("需要Token，请登陆！");
            }

            Integer userId = AuthUtil.getUserId(token);
            User user = userService.getUserById(userId);
            if (user == null) {
                throw new RuntimeException("Token无效，请重新登陆！");
            }

            //验证Token
            AuthUtil.verify(token, user.getPassword());
        }

        return true;
    }
}
